package com.lean.demo.service.impl;

import com.lean.demo.config.mapper.AreaMapper;
import com.lean.demo.entity.Area;
import com.lean.demo.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class AreaServiceImpl implements AreaService {
    @Autowired
    private AreaMapper areaMapper;

    @Override
    public Area queryAreaById(Integer id) {
        Area area = (Area) areaMapper.queryAreaById(id);
        System.out.println(area);
        return area;
    }

    @Override
    public List<Area> queryAreas() {
        return areaMapper.queryAreas();
    }

    @Override
    @Transactional
    public boolean editArea(Area area) {
        if (area.getAreaId() != null && area.getAreaId()>0) {
            area.setLastEditTime(new Date());
            try {
                int effectedNum = areaMapper.updateArea(area);
                if (effectedNum > 0) {
                    return true;
                } else {
                    throw new RuntimeException("更新区域信息失败");
                }
            } catch (RuntimeException e) {
                throw new RuntimeException("更新区域信息失败" + e.getMessage());
            } finally {

            }
        }else{
            throw new RuntimeException("区域信息不能为空！");
        }
    }

    @Override
    public boolean deleteAreaById(Integer id) {
        if (id != null && id>0) {
            try {
                int effectedNum = areaMapper.deleteAreaById(id);
                if (effectedNum > 0) {
                    return true;
                } else {
                    throw new RuntimeException("删除区域信息失败");
                }
            } catch (RuntimeException e) {
                throw new RuntimeException("删除区域信息失败" + e.getMessage());
            } finally {

            }
        }else{
            throw new RuntimeException("区域信息不能为空！");
        }
    }

    @Override
    @Transactional
    public boolean addArea(Area area) {
        if (area.getAreaName() != null && !area.getAreaName().equals("")) {
            area.setCreateTime(new Date());
            area.setLastEditTime(new Date());
            try {
                int effectedNum = areaMapper.insertArea(area);
                if (effectedNum > 0) {
                    return true;
                } else {
                    throw new RuntimeException("插入区域信息失败");
                }
            } catch (RuntimeException e) {
                throw new RuntimeException("插入区域信息失败" + e.getMessage());
            } finally {

            }
        }else{
            throw new RuntimeException("区域信息不能为空！");
        }
    }
}
